package com.iteaj.iot.server.websocket.impl;

import com.iteaj.iot.server.ServerProtocolHandle;
import com.iteaj.iot.server.websocket.WebSocketServerListener;
import com.iteaj.iot.websocket.WebSocketException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class DefaultWebSocketServerProtocolHandle implements ServerProtocolHandle<DefaultWebSocketServerProtocol> {

    private Logger logger = LoggerFactory.getLogger(getClass());
    private Map<String, WebSocketServerListener> listeners;

    public DefaultWebSocketServerProtocolHandle(Map<String, WebSocketServerListener> listeners) {
        this.listeners = listeners;
    }

    @Override
    public Object handle(DefaultWebSocketServerProtocol protocol) {
        DefaultWebSocketServerMessage requestMessage = protocol.requestMessage();
        WebSocketServerListener listener = listeners.get(requestMessage.uri());
        if(listener != null) {
            switch (requestMessage.frameType()) {
                case Text:
                    listener.onText(protocol); break;
                case Binary:
                    listener.onBinary(protocol); break;
                case Close:
                    listener.onClose(protocol); break;
                default: throw new WebSocketException("不支持的事件["+requestMessage.frameType()+"]");
            }
        } else {
            this.logger.warn("WebSocket 未找到监听器(请确认uri是否完全匹配) - uri：{} - cause：将导致无法处理此uri的请求", requestMessage.uri());
        }

        return null;
    }

}
